package cn.com.taiji.pos.controller.Abandoned;

import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.pos.entity.*;
import cn.com.taiji.pos.service.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

//@RestController
//@RequestMapping("/GiveFood")
public class GiveFoodController {
    @Value("${SETTLEMENT_TYPE_ID_zengcai}")
    private String SETTLEMENT_TYPE_ID_zengcai;
    @Autowired
    private ISystemPosMachineService systemPosMachineService;
    @Autowired
    private IConfigMealTimeService configMealTimeService;
    @Autowired
    private ICardInfoService cardInfoService;
    @Autowired
    private ITradeAccountConsumptionFlowService tradeAccountConsumptionFlowService;
    @Autowired
    private ITradeConsumptionDetailService tradeConsumptionDetailService;
    @Autowired
    private IMenuFoodPriceService menuFoodPriceService;
    @Autowired
    private ITradeConsumptionMainService tradeConsumptionMainService;


    /**
     * 赠菜
     *
     * @param model
     * @param data
     * @param request
     * @param response
     */
    @RequestMapping(value = "GiveFood", method = RequestMethod.POST)
    @Transactional
    public String retreatFood(Model model, @RequestBody JSONObject data, HttpServletRequest request, HttpServletResponse response) throws Exception {
        model.addAttribute("result", "fail");
        String canci = data.getString("canci");
        String reason = data.getString("reason");
        String customerName = data.getString("customerName");
        String cardCode = data.getString("cardCode");
        String physicalCode = data.getString("physicalCode");
        List<ItemS> itemSList = JSONArray.parseArray(data.getJSONArray("GiveFoodIdList").toString(), ItemS.class);
        CardInfo cardInfo = cardInfoService.findByCardCode(cardCode);
        if (cardInfo == null) {
            model.addAttribute("message", "未找到该卡片所对应客户!");
            return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
        } else if (!StringUtils.hasText(reason)) {
            model.addAttribute("message", "赠菜原因不能为空!");
            return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
        } else if (!StringUtils.hasText(customerName)) {
            model.addAttribute("message", "客户名称不能为空!");
            return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
        }

        SystemAclUser user = (SystemAclUser) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        TradeAccountConsumptionFlow tradeAccountConsumptionFlow = new TradeAccountConsumptionFlow();

        SystemPosMachine posMachine = systemPosMachineService.findByPhysicalCode(physicalCode);
        ConfigMealTime configMealTime = configMealTimeService.findByName(canci);
        tradeAccountConsumptionFlow.setRestaurantId(posMachine.getRestaurantId());
        tradeAccountConsumptionFlow.setPosMachineId(posMachine.getId());
        tradeAccountConsumptionFlow.setMealTimeId(configMealTime.getId());
        tradeAccountConsumptionFlow.setOperateType(2);//赠菜
        tradeAccountConsumptionFlow.setSettlementTypeId("");
        tradeAccountConsumptionFlow.setSettlementTypeId(SETTLEMENT_TYPE_ID_zengcai);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        tradeAccountConsumptionFlow.setFlowNo("ZC-" + posMachine.getId() + posMachine.getCode() + configMealTime.getCode() + df.format(LocalDateTime.now()) + UUID.randomUUID().toString().substring(0, 4));
        tradeAccountConsumptionFlow.setIsPay("0");
        tradeAccountConsumptionFlow.setCardId(cardInfo.getId());
        tradeAccountConsumptionFlow.setCustomerId(cardInfo.getCustomerId());
        tradeAccountConsumptionFlow.setCreatorId(user.getId());
        tradeAccountConsumptionFlow.setCreatorName(user.getName());
        tradeAccountConsumptionFlow.setBeforeAmount(BigDecimal.ZERO);
        tradeAccountConsumptionFlow.setAfterAmount(BigDecimal.ZERO);
        tradeAccountConsumptionFlow.setActualAmount(0.0);
        tradeAccountConsumptionFlow.setReasonId(reason);
        tradeAccountConsumptionFlow.setCreateTime(LocalDateTime.now());
        insertInto(itemSList, tradeAccountConsumptionFlow, user);
        tradeAccountConsumptionFlowService.save(tradeAccountConsumptionFlow);
        model.addAttribute("result", "success");
        model.addAttribute("message", "赠菜成功");
        return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
    }

    //增加消费主单明细单
    private void insertInto(List<ItemS> itemsList, TradeAccountConsumptionFlow tradeAccountConsumptionFlow, SystemAclUser user) throws Exception {
        List<TradeConsumptionDetail> detailList = new ArrayList<>();
        TradeConsumptionMain tradeConsumptionMain = new TradeConsumptionMain();
        tradeConsumptionMain.setRestaurantId(tradeAccountConsumptionFlow.getRestaurantId());
        tradeConsumptionMain.setMealTimeId(tradeAccountConsumptionFlow.getMealTimeId());
        tradeConsumptionMain.setPosMachineId(tradeAccountConsumptionFlow.getPosMachineId());
        tradeConsumptionMain.setFlowNo(tradeAccountConsumptionFlow.getFlowNo());
        tradeConsumptionMain.setConsumptionTime(LocalDateTime.now());
        tradeConsumptionMain.setOrderType(2);
        double count = 0;
        double money = 0.0;
        for (ItemS items : itemsList) {
            count += items.getCount();
            money += items.getAmount();
        }
        tradeConsumptionMain.setQuantity(count);
        tradeConsumptionMain.setShouldPaidAmount(0.0);
        tradeConsumptionMain.setActualAmount(0.0);
        tradeConsumptionMain.setDiscountPercent(BigDecimal.ZERO);
        tradeConsumptionMain.setReasonId("菜品赠送");
        tradeConsumptionMain.setQuotaPrice(BigDecimal.ZERO);
        tradeConsumptionMain.setTimes(0);
        tradeConsumptionMain.setIsSettlement("1");
        tradeConsumptionMain.setCreatorId(user.getId());
        tradeConsumptionMain.setCreatorName(user.getName());
        tradeConsumptionMain.setCreateTime(LocalDateTime.now());
        tradeConsumptionMainService.save(tradeConsumptionMain);
        for (ItemS itemS : itemsList) {
            TradeConsumptionDetail tradeConsumptionDetail = new TradeConsumptionDetail();
            tradeConsumptionDetail.setQuantity(itemS.getCount());
            tradeConsumptionDetail.setHandDiscount(BigDecimal.ZERO);
            tradeConsumptionDetail.setReasonId("");
            tradeConsumptionDetail.setActualAmount(new BigDecimal(itemS.getCount() * itemS.getPrice()));
            tradeConsumptionDetail.setMainId(tradeConsumptionMain.getId());
            tradeConsumptionDetail.setPrice(new BigDecimal(itemS.getPrice()));
            QueryWrapper<MenuFoodPrice> menuFoodPriceWrapper = new QueryWrapper<>();
//            menuFoodPriceWrapper.eq("MEAL_TIME_ID",tradeAccountConsumptionFlow.getMealTimeId());
            menuFoodPriceWrapper.eq("FOOD_ID", itemS.getIds());
            MenuFoodPrice menuFoodPrice = menuFoodPriceService.getOne(menuFoodPriceWrapper);
            if (menuFoodPrice != null) {
                tradeConsumptionDetail.setBusinessTypeId(menuFoodPrice.getBusinessTypeId());
                tradeConsumptionDetail.setFoodId(menuFoodPrice.getFoodId());
            } else {
                tradeAccountConsumptionFlowService.removeById(tradeAccountConsumptionFlow.getId());
                tradeConsumptionMainService.removeById(tradeConsumptionMain.getId());
                throw new Exception("未查询到该菜品");
            }
            detailList.add(tradeConsumptionDetail);
        }
        tradeConsumptionDetailService.saveBatch(detailList);
    }


}
